//
//  GHPlayerView.m
//  GHPlayer
//
//  Created by GH on 16/3/21.
//  Copyright © 2016年 GH. All rights reserved.
//

#import "GHPlayerView.h"

@interface GHPlayerView ()

@property (nonatomic ,assign)BOOL singleClick;
@property (nonatomic ,assign)BOOL doubleClick;
@property (nonatomic ,retain)id timeObser;
@property (nonatomic ,retain)NSString *timeStr;


@end

@implementation GHPlayerView






- (AVPlayerItem *)getPlayerItemWithUrlstring:(NSString *)urlstr {

    NSString *str = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:str]];
    
    return playerItem;
}


- (instancetype)initWithFrame:(CGRect)frame videoWithUrlstr:(NSString *) urlstr {

    self = [super initWithFrame:frame];
    
    if (self) {

        self.playeritem = [self getPlayerItemWithUrlstring:urlstr];
        self.backgroundColor = [UIColor blackColor];
        
        //Avplayer
        
        self.player = [AVPlayer playerWithPlayerItem:self.playeritem];
        self.playerlayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.playerlayer.frame = self.bounds;
        [self.layer addSublayer:self.playerlayer];
        self.playerlayer.videoGravity = AVLayerVideoGravityResizeAspect;
        [self.player play];
        
        
        //bottomView
        self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 40, self.frame.size.width, 40)];
        [self addSubview:self.bottomView];
        self.bottomView.backgroundColor = [UIColor redColor];
        self.bottomView.alpha = 0;
        UIButton * ButtionWithPlay = [UIButton buttonWithType:UIButtonTypeSystem];
        ButtionWithPlay.frame = CGRectMake(10, 5, 30, 30);
        ButtionWithPlay.backgroundColor = [UIColor grayColor];
        [self.bottomView addSubview:ButtionWithPlay];
        [ButtionWithPlay addTarget:self action:@selector(palyOrpanse:) forControlEvents:UIControlEventTouchUpInside];
        //slider
        self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(45, 5, self.bounds.size.width /2, 30)];
        [self.bottomView addSubview:self.progressSlider];
        [self.progressSlider setThumbImage:[UIImage imageNamed:@"dot"] forState:UIControlStateNormal];
        self.progressSlider.minimumTrackTintColor = [UIColor colorWithRed:0.291 green:0.503 blue:1.000 alpha:1.000];
        
        [self.progressSlider addTarget:self action:@selector(sliderUpData:) forControlEvents:UIControlEventValueChanged];
        
        self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.bounds.size.width /2+50, 5, self.bounds.size.width /4, 30)];
        [self.bottomView addSubview:self.timeLabel];
        self.timeLabel.backgroundColor = [UIColor colorWithRed:1.000 green:0.333 blue:0.642 alpha:1.000];
        self.timeLabel.text = @"00:00/00:00";
        self.timeLabel.textColor = [UIColor whiteColor];
        
        //手势
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        singleTap.numberOfTapsRequired = 1;
        [self addGestureRecognizer:singleTap];
        
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
        doubleTap.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleTap];
        
       [self addProgressObserver];
        
    }

    return self;

}

//slider 滑动

- (void)sliderUpData:(UISlider *)slider {

    
    if (slider.value) {
        
    
//    [self removeObserver];
    CGFloat all = [self duration];
    double currentTime = all *slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        
        [self.player play];
        
    }];
//    [self progressSlider];
    }
}

//单击
- (void)singleTap:(UIGestureRecognizer *)single {

    if (self.bottomView.alpha == 0) {
    
        [UIView animateWithDuration:0.3 animations:^{
            self.bottomView.alpha = 1;
        }];
    }else {
        [UIView animateWithDuration:0.3 animations:^{
            self.bottomView.alpha = 0;
        }];
    }
}

//双击
- (void)doubleTap:(UIGestureRecognizer *)doubleTap {

    if (self.player.rate != 1) {
        if ([self currentTime] == [self duration]) {
            [self setCurrentTime:0];
        }
        [self.player play];
    }else {
    
        [self.player pause];
    }
}

//button点击事件
- (void)palyOrpanse:(UIButton *)button {
    if (self.player.rate != 1) {
        if ([self currentTime] == [self duration]) {
            [self setCurrentTime:0];
        }
        [self.player play];
    }else {
        
        [self.player pause];
    }


}

//返回整个视频时间
- (double)duration{
    AVPlayerItem *playerItem = self.player.currentItem;
    if (playerItem.status == AVPlayerItemStatusReadyToPlay){
        return CMTimeGetSeconds([[playerItem asset] duration]);
    }
    else{
        return 0.f;
    }
}

//当前时间
- (double)currentTime{
    return CMTimeGetSeconds([[self player] currentTime]);
}

- (void)setCurrentTime:(double)time{
    [[self player] seekToTime:CMTimeMakeWithSeconds(time, 1)];
}


- (void)addProgressObserver {

    __weak GHPlayerView *view = self;
    
_timeObser = [view.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
   
    
 CGFloat duration = CMTimeGetSeconds(self.playeritem.duration);
    CGFloat current = CMTimeGetSeconds(self.playeritem.currentTime);
    //倒计时
    CGFloat rem = duration - current;
    
    NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
    NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
    
    self.timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
    NSLog(@"%@",self.timeStr);
    
    self.progressSlider.value = current / duration;
}];

}



- (void)removeObserver {
    [self.player removeTimeObserver:_timeObser];

}

- (void)layoutSubviews {

    [super layoutSubviews];
    self.timeLabel.text = self.timeStr;

}


@end
